<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="formData.id ? '编辑员工' : '新增员工'"
    v-model="dialogVisible"
    width="500px"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入员工姓名" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="formData.phone"
          :controls="false"
          :min="0"
          placeholder="请输入员工手机号"
        />
      </el-form-item>
      <el-form-item label="sku角色" prop="skuIds">
        <el-select v-model="formData.skuIds" multiple>
          <el-option
            v-for="item in skusList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { postUsers, putUsers } from '@/api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  skusList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['submit'])

const dialogVisible = ref(false)
const formRef = ref(null)

const formData = reactive({
  id: undefined,
  name: '',
  phone: '',
  skuIds: []
})

const rules = {
  name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入员工手机号', trigger: 'blur' }],
  skuIds: [{ required: true, message: '请选择SKU角色', trigger: 'change' }]
}

const open = (data) => {
  // 重置表单数据
  Object.assign(formData, {
    id: undefined,
    name: '',
    phone: '',
    skuIds: []
  })

  // 如果有传入数据，则更新表单
  if (data) {
    Object.assign(formData, {
      id: data.id,
      name: data.name,
      phone: data.phone,
      skuIds: data.skus.map((item) => item.id)
    })
  }

  dialogVisible.value = true
}

const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (formData.id) {
        await putUsers(formData)
      } else {
        await postUsers(formData)
      }
      emit('submit')
      handleClose()
      ElMessage.success('操作成功！')
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  })
}

// 暴露方法给父组件
defineExpose({
  open
})
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-input-number) {
  .el-input__inner {
    text-align: left !important;
  }
}
</style>
